package org.com.ashen.service.util;

import java.io.BufferedInputStream;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

public class GetRequsetUrl {
	public static String getPostParam(HttpServletRequest request) {
		String sret = null;
		if (request.getQueryString() != null) {
			sret = "http://" + request.getServerName() // 服务器地址
					+ ":" + request.getServerPort() // 端口号
					+ request.getContextPath() // 项目名称
					+ request.getServletPath() // 请求页面或其他地址
					+ "?" + (request.getQueryString()); // 参数

		} else {
			String ContentType = "";
			ContentType = request.getHeader("Content-Type");
			if (ContentType.equalsIgnoreCase("application/x-www-form-urlencoded") || ContentType.equalsIgnoreCase("application/x-www-form-urlencoded;")) {
				Map<String, String[]> params = request.getParameterMap();
				String queryString = "";
				for (String key : params.keySet()) {
					String[] values = params.get(key);
					for (int i = 0; i < values.length; i++) {
						String value = values[i];
						queryString += key + "=" + value + "&";
					}
				}

				if (queryString.length() > 1) {
					// 去掉最后一个空格
					queryString = queryString.substring(0,queryString.length() - 1);
				}
				sret = queryString;

			} else if (ContentType.equalsIgnoreCase("multipart/form-data") || ContentType.equals("multipart/form-data;")) {
				try {
					StringBuffer info = new StringBuffer();
					ServletInputStream in = request.getInputStream();
					BufferedInputStream buf = new BufferedInputStream(in);
					byte[] buffer = new byte[1024];
					int iRead;
					while ((iRead = buf.read(buffer)) != -1) {
						info.append(new String(buffer, 0, iRead, "UTF-8"));
						sret = info.toString();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			sret = "http://" + request.getServerName() // 服务器地址
					+ ":" + request.getServerPort() // 端口号
					+ request.getContextPath() // 项目名称
					+ request.getServletPath() // 请求页面或其他地址
					+ "?" + sret; // 参数
		}
		return sret;
	}
	
	
	
	public static String getServer(HttpServletRequest request) {
		String sret = null;
		sret = "http://" + request.getServerName() // 服务器地址
		+ ":" + request.getServerPort() // 端口号
		+ request.getContextPath() // 项目名称
		+ request.getServletPath() // 请求页面或其他地址
		+ "?"; // 参数
		return sret;
	}
}
